package com.zjw.service.impl;

import com.zjw.dao.GoodsDao;
import com.zjw.dao.TradeLogDao;
import com.zjw.dao.impl.GoodsDaoImpl;
import com.zjw.dao.impl.TradelogDaoImpl;
import com.zjw.dao.impl.UserDaoImpl;
import com.zjw.entity.TradeLog;
import com.zjw.entity.User;
import com.zjw.dao.UserDao;
import com.zjw.service.UserService;
import com.zjw.utils.ConnectionUtil;
import com.zjw.utils.Constants;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 普通用户信息表(User)表服务实现类
 *
 * @author 翟
 * @since 2025-04-09 08:59:19
 */
public class UserServiceImpl implements UserService {

    @Override
    public User login(String username, String password) {
        Connection conn = ConnectionUtil.getConnection();
        User user = null;
        UserDao userDao = new UserDaoImpl(conn);
        try {
            user = userDao.selectUserByUsernameAndPassword(username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionUtil.closeALL(null , null , conn);
        }
        return user;
    }

    @Override
    public boolean modifyBalanceByUserId(double money , TradeLog tradeLog) {
        Connection conn = ConnectionUtil.getConnection();
        ConnectionUtil.beginTransaction(conn);
        UserDao userDao = new UserDaoImpl(conn);
        TradeLogDao tradeLogDao = new TradelogDaoImpl(conn);
        GoodsDao goodsDao = new GoodsDaoImpl(conn);
        try {
            userDao.updateBalanceByUserId(tradeLog.getSellerId(), money , Constants.ADDITION_BALANCE);
            userDao.updateBalanceByUserId(tradeLog.getBuyerId() , money , Constants.REDUCE_BALANCE);
            tradeLogDao.insert(tradeLog);
            goodsDao.updateIsOnSellByGoodsId(tradeLog.getGoodsId());
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("数据库出问题了！！！");
            //回滚事务
            ConnectionUtil.rollbackTransaction(conn);
        }finally {
            //提交事务
            ConnectionUtil.commitTransaction(conn);
            ConnectionUtil.closeALL(null , null , conn);
        }
        return false;
    }


}
